<template>
  <div class="image-upload-box">
    <el-upload
      action="#"
      list-type="picture-card"
      :http-request="uploadFn"
      :file-list="fileList"
      :limit="num"
      :on-remove="removeFn"
      :on-change="changeFn"
      :class="{'image-upload': fileList.length > num-1}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress
      v-if="percent > 0 && percent < 100"
      :width="100"
      type="circle"
      :percentage="percent"
    />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDiLpBRaYGk29nQxJmJhs3A9yZ9g3GQM9n',
  SecretKey: 'b3MVaZQ4Vn2750mRqiRxLbhcOwPhqogO'
})
export default {
  props: {
    num: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      percent: 0 // 当前上传进度
    }
  },
  methods: {
    // 移除图片
    removeFn(data, index) {
      this.fileList = index
    },
    changeFn(data, index) {
      this.fileList = index
    },
    // 上传图片
    uploadFn(res) {
      cos.putObject(
        {
          Bucket: 'cjwd-hr-1313158691' /* 必须---储存桶名字 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() + 'geng', /* 必须--上传腾讯云后的文件名--字符串 */
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            //   console.log(JSON.stringify(progressData))
            this.percent = +(progressData.percent * 100).toFixed(2)
          }
        },
        (err, data) => {
          console.log(data)
          if (!err) {
            // this.fileList.splice(this.fileList.length - 1, 1, { url: 'http://' + data.Location })
            console.log('上传成功')
            // 修改 fileList 将腾讯云的地址存起来备用
            this.fileList.forEach(element => {
              // 根据 uid 找出当前正在上传的图片 修改路径和状态
              if (element.uid === res.file.uid) {
                element.url = 'http://' + data.Location
                element.status = 'success'
              }
            })
          }
        }
      )
    }
  }
}
</script>

<style lang="scss">
.image-upload-box {
  position: relative;
  display: inline-block;
  .el-progress {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -55%);
  }
}
.image-upload {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
